package com.gwz.cardserver.logic;

import com.gwz.cardserver.consts.MatchCodeConst;
import com.gwz.cardserver.dto.ReqBase;
import com.gwz.cardserver.dto.ResBase;
import com.gwz.cardserver.dto.match.MatchRoomDTO;
import com.gwz.cardserver.service.MatchService;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MatchHandler implements IHandler {
    @Autowired
    private MatchService matchService;
    @Override
    public void channelRead(ChannelHandlerContext ctx, ReqBase reqBase) {
        switch (reqBase.getSubCode()) {
            case MatchCodeConst.ENTER: {
                MatchRoomDTO matchRoomDTO = matchService.enter(ctx,reqBase);
                ctx.writeAndFlush(ResBase.success(reqBase, matchRoomDTO));
                break;
            }
            case MatchCodeConst.LEAVE: {
                matchService.leave(ctx, reqBase);
                break;
            }
            case MatchCodeConst.READY: {
                try {
                    matchService.ready(ctx, reqBase);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            }

        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        matchService.removeUserByChannel(ctx);
    }
}
